package com.szsfm.vehiclemanagement.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.wintone.plateid.RecogService;


/**
 * 车牌识别的工具方法
 */

public class RecogCarNumberUtils implements ServiceConnection {

    public RecogService.MyBinder recogBinder;
    private Context context;
    private Handler handler;
    // 调用方法的配置
    private int iInitPlateIDSDK = -1;
    private int imageformat = 1;
    private int bVertFlip = 0;
    private int bDwordAligned = 1;
    private String[] fieldvalue = new String[14];
    private int nRet = -1;
    private String recogPicPath;
    private boolean bGetVersion = false;

    // 初始化构造方法
    public RecogCarNumberUtils(Context context, Handler handler, String recogPicPath) {
        this.context = context;
        this.handler = handler;
        this.recogPicPath = recogPicPath;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

        recogBinder = (RecogService.MyBinder) service;
        // recogPicPath = "/storage/sdcard0/carnumber.jpg";
        // 调用函数成功为0；
        iInitPlateIDSDK = recogBinder.getInitPlateIDSDK();
        Log.v("iInitPlateIDSDK----", "" + iInitPlateIDSDK);
        if (iInitPlateIDSDK != 0) {//失败
            handler.sendEmptyMessage(2);
            return;
        } else {
            // 开启识别服务
            startRecogCarNumber();
        }

        if (recogBinder != null) {
            context.unbindService(this);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        recogBinder = null;
    }

    /**
     * 开始识别车牌
     */
    private void startRecogCarNumber() {
        recogBinder.setRecogArgu(recogPicPath, imageformat,
                bGetVersion, bVertFlip, bDwordAligned);

        nRet = recogBinder.getnRet();
        // 返回的识别结果值
        fieldvalue = recogBinder.doRecog(recogPicPath, 480, 800);

        nRet = recogBinder.getnRet();
        Log.e("nRet", nRet + "");

        if (nRet != 0) {//识别失败
            handler.sendEmptyMessage(2);
            return;
        } else {
            hanlderAnalysisResult();
        }
    }

    /**
     * 分析返回的结果
     */
    private void hanlderAnalysisResult() {
        String car_Id = fieldvalue[0];
        if (car_Id != null) {
            // 界面返回车牌号显示
            car_Id = car_Id.toUpperCase();
            String carColor = fieldvalue[1];
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("CarNumber", car_Id);
            bundle.putString("CarColor",carColor);
            msg.what = 1;
            msg.setData(bundle);
            handler.sendMessage(msg);
        } else {
            //失败
            handler.sendEmptyMessage(2);
        }
    }
}
